document.addEventListener("DOMContentLoaded", () => {
  const form = document.getElementById("csForm");
  const tbody = document.getElementById("resultBody");

  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    const api = form.dataset.api || "/api/analysis/cs2/";
    const params = new URLSearchParams(new FormData(form));
    let payload;

    try {
      if (window.ANALYSIS_DEMO) {
        payload = demoData();             // 本地演示数据
      } else {
        const res = await fetch(`${api}?${params.toString()}`, { method: "GET" });
        if (!res.ok) throw new Error("网络错误");
        payload = await res.json();       // 期望后端返回 { items: [...], kpis: {...} }
      }
      renderKPIs(payload.kpis || {});
      renderTable(payload.items || []);
    } catch (err) {
      renderError(err.message || "分析失败");
    }
  });

  function renderKPIs(k) {
    setText("kpiPlatforms", k.platforms ?? "—");
    setText("kpiItems",     k.items ?? "—");
    setText("kpiAvgSpread", k.avg_spread != null ? formatMoney(k.avg_spread) : "—");
    setText("kpiBest",      k.best ?? "—");
  }

  function renderTable(rows) {
    if (!rows.length) {
      tbody.innerHTML = `<tr class="text-muted"><td colspan="7">没有找到符合条件的结果</td></tr>`;
      return;
    }
    tbody.innerHTML = rows.map(r => {
      const pfBadge = platformBadge(r.platform);
      const spread = numberLike(r.spread_vs_steam) ? r.spread_vs_steam : null;
      const spreadCls = spread == null ? "" : (spread < 0 ? "spread-pos" : "spread-neg");
      const spreadTxt = spread == null ? "—" : (spread > 0 ? "+" : "") + formatMoney(spread);

      return `
        <tr>
          <td>${escapeHTML(r.name || "")}</td>
          <td>${escapeHTML(r.exterior || "")}</td>
          <td>${pfBadge}</td>
          <td class="text-end">${formatMoney(r.price)}</td>
          <td class="text-end ${spreadCls}">${spreadTxt}</td>
          <td class="text-end">${r.volume ?? "—"}</td>
          <td>${r.updated || "—"}</td>
        </tr>`;
    }).join("");
  }

  function renderError(msg) {
    tbody.innerHTML = `<tr><td colspan="7"><div class="alert alert-danger mb-0">${escapeHTML(msg)}</div></td></tr>`;
  }

  // —— 小工具 —— //
  function setText(id, v){ const el = document.getElementById(id); if (el) el.textContent = v; }
  function formatMoney(n){
    if (!numberLike(n)) return "—";
    return (n >= 0 ? "" : "-") + "￥" + Math.abs(+n).toFixed(2);
  }
  function numberLike(v){ return typeof v === "number" || (typeof v === "string" && v.trim() && !isNaN(v)); }
  function escapeHTML(s){ return String(s).replace(/[&<>"']/g,m=>({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[m])); }
  function platformBadge(pf){
    const map = {
      steam:  '<span class="badge badge-pf badge-steam">Steam</span>',
      buff:   '<span class="badge badge-pf badge-buff">Buff</span>',
      c5:     '<span class="badge badge-pf badge-c5">C5</span>',
      skinport:'<span class="badge badge-pf badge-skinport">SkinPort</span>',
      haloskins:'<span class="badge badge-pf badge-halo">HaloSkins</span>'
    };
    return map[(pf||"").toLowerCase()] || `<span class="badge bg-secondary">未知</span>`;
  }

  // —— 本地演示数据（无后端也能跑） —— //
  function demoData(){
    const items = [
      { name:"Glock-18 | Neo-Noir", exterior:"Well-Worn", platform:"buff", price: 85.20, spread_vs_steam:-12.30, volume: 56, updated:"刚刚" },
      { name:"AK-47 | Slate", exterior:"Field-Tested", platform:"steam", price: 32.10, spread_vs_steam: 0.00, volume: 140, updated:"5 分钟前" },
      { name:"M4A4 | Eye of Horus", exterior:"Minimal Wear", platform:"skinport", price: 2899.00, spread_vs_steam:-210.50, volume: 6, updated:"1 小时前" },
      { name:"USP-S | Printstream", exterior:"Minimal Wear", platform:"buff", price: 410.00, spread_vs_steam:-35.40, volume: 22, updated:"3 小时前" },
    ];
    return {
      items,
      kpis: {
        platforms: 4,
        items: items.length,
        avg_spread: items.reduce((a,b)=>a+(b.spread_vs_steam||0),0)/items.length,
        best: "M4A4 | Eye of Horus"
      }
    };
  }
});